package br.com.intelsys.basics.dao.hiber;

import java.io.Serializable;

import org.hibernate.Criteria;
import org.hibernate.Session;

import br.com.intelsys.basics.dao.QueryManager;
import br.com.intelsys.basics.dao.QueryManagerMaker;
import br.com.intelsys.basics.dao.Trans;

public class QueryManagerHibernateTemplate implements QueryManager {
	private final DaoHiber daoHiber;

	public QueryManagerHibernateTemplate(final DaoHiber hibernateDaoSupport) {
		this.daoHiber = hibernateDaoSupport;
	}

	Session getSession() {
		return daoHiber.getLocalSession();
	}

	public Object get(final Class<?> entityClass, final Serializable id) {
		return getSession().get(entityClass, id);
	}

	public void saveOrUpdate(Object entity) {
		saveOrUpdateAndAfterRefresh(entity, (Object[]) null);
	}

	public void saveOrUpdateAndAfterRefresh(Object entity, Object... refreshObject) {
		Trans t = beginTransaction();
		t.saveOrUpdate(entity);
		t.commit();
		t.refreshList(refreshObject);
	}

	public void delete(Object entity) {
		Trans t = beginTransaction();
		t.delete(entity);
		t.commit();
	}

	public void deleteAfterRefresh(Object entity, Object... refreshObject) {
		Trans t = beginTransaction();
		t.delete(entity);
		t.commit();
		t.refreshList(refreshObject);
	}

	public QueryManagerMaker find(String queryName) {
		return new QueryManagerMakerHibernateTemplate(this, queryName);
	}

	public Trans beginTransaction() {
		return new TransHiber(daoHiber);
	}

	public Criteria createCriteria(Class<?> clazz) {
		return getSession().createCriteria(clazz);
	}
}
